from .log import log_gui

ON_ENTER = "OnEnter"
ON_EXIT = "OnExit"
debug = True

class State:
  def __init__(self, name):
    self.name = name
    self.events = {}

  def SetEventCb(self, event, cb=None, next=None):
    self.events[event] = (cb, next)

  def Notify(self, event, data=None):
    if debug:
      log_gui(self.name,"got event",event,"with data",data)
    next = None
    if event in self.events:
      cb, next = self.events[event]
      if cb:
        if debug:
          log_gui(self.name,"running associated state callback", cb)
        cb(event, data)
    return next

class Machine:
  def __init__(self, initial_state):
    self._initial_state = initial_state
    self.Reset()

  def Event(self, event, data=None):
    new_state = self.state.Notify(event, data)
    if debug and not new_state:
      log_gui("No state transition")
    while new_state:
      if debug:
        log_gui("Transitioning to state", new_state.name)
      self.state.Notify(ON_EXIT)
      self.state = new_state
      new_state = new_state.Notify(ON_ENTER)

  def Reset(self):
    self.state = self._initial_state
